/*
 * Server.h
 *
 *  Created on: 2009-02-12
 *      Author: ck
 */

#ifndef SERVER_H_
#define SERVER_H_
#include <QTcpServer>
#include <QSet>
#include <QTimer>
#include "ConnectionPlayer.h"
#include "ServerPlayer.h"


class Server : public QTcpServer {
	Q_OBJECT

public:

	Server(QObject *parent = 0);
	bool start(int port);
	virtual ~Server();
	void sendPeopleList(ConnectionPlayer* conn); //do tego w parametrze wysle cala liste, do reszty wiadomosc JOIN nick
	void sendPlayerLeft(ConnectionPlayer* conn);
	void sendToAll(QString cmd, QStringList args = QStringList(), ConnectionPlayer* conn = 0);
protected:
	void incomingConnection ( int socketDescriptor );
signals:
	void newConnection(ConnectionPlayer *connection);

public slots:
	void onNewMessage(ConnectionPlayer* conn, QString cmd, QStringList args);
	void onSocketDisconnected(ConnectionPlayer*);
	void onTimeOut();

private:
	enum GameState { gameNotStarted, roundFinished, gameStarted };

	QVector<ConnectionPlayer*> players; //max 4
	QVector<ServerPlayer*> jamPlayers;
	QVector<ConnectionPlayer*> spectators;
	QSet<QString> nickSet;//zbior nickow, pomocny przy wykrywaniu czy jakis sie nie powtarza

	int foodCount; //2x wiecej niz jamnikow
	short board[20][20]; //0 - nic, 1-jakis jamnik, 2-jedzenie
	GameState gameState;
	QTimer timer;

	void updateConnId();
	void checkAllReady();
	void startGame();
	void sendPlayersStartPos();
	void sendDirs();
	void sendTick();
	void clearBoard();
	void initPlayersBoard();
	void initJamPlayers();
	void randomizeFood();
	QString makeXYStr(int x, int y);
};

#endif /* SERVER_H_ */
